package com.zlp.mall.portal.modules.ums.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlp.mall.common.api.RespCode;
import com.zlp.mall.common.enums.StatusEnum;
import com.zlp.mall.common.exception.Asserts;
import com.zlp.mall.common.exception.CustomException;
import com.zlp.mall.common.redis.RedisService;
import com.zlp.mall.common.util.BeanToUtils;
import com.zlp.mall.common.util.MethodUtil;
import com.zlp.mall.portal.modules.ums.dto.req.MemberAddReq;
import com.zlp.mall.portal.modules.ums.dto.resp.MemberResp;
import com.zlp.mall.portal.modules.ums.mapper.MemberMapper;
import com.zlp.mall.portal.modules.ums.model.Member;
import com.zlp.mall.portal.modules.ums.model.MemberLoginLog;
import com.zlp.mall.portal.modules.ums.service.MemberLoginLogService;
import com.zlp.mall.portal.modules.ums.service.MemberService;
import com.zlp.mall.portal.security.dto.MemberDetails;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author ZouLiPing
 * @since 2021-10-15
 */
@Service
@RequiredArgsConstructor
@Slf4j(topic = "MemberServiceImpl")
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    private final MemberLoginLogService memberLoginLogService;
    private final RedisService redisService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public MemberResp register(MemberAddReq memberAddReq) {

        log.info("register.req memberAddReq={}", JSON.toJSONString(memberAddReq));
        Member member = BeanToUtils.dtoToDo(memberAddReq, Member.class);
        member.setStatus(StatusEnum.NORMAL.getValue());
        //查询是否有相同用户名的用户
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Member::getUsername, memberAddReq.getUsername());
        int count = this.count(wrapper);
        if (count > 0) {
            throw new CustomException(RespCode.FRONT_SYS_2000, MethodUtil.getLineInfo());
        }
        //将密码进行加密操作
        String encodePassword;
        try {
            encodePassword = BCrypt.hashpw(memberAddReq.getPassword());
        } catch (Exception e) {
            log.error("BCrypt.hashpw.resp error={}", e.getMessage());
            throw new CustomException(RespCode.FRONT_SYS_2002, MethodUtil.getLineInfo());
        }
        member.setPassword(encodePassword);
        this.save(member);
        if (Objects.isNull(member.getId())) {
            throw new CustomException(RespCode.FRONT_SYS_2001, MethodUtil.getLineInfo());
        }
        return BeanToUtils.doToDto(member, MemberResp.class);
    }

    @Override
    public Member login(String username, String password) {

        log.info("login.req username={},password={}", username, password);
        //密码需要客户端加密后传递
        MemberDetails userDetails = null;
        try {
            userDetails = loadMemberByUsername(username);
            if (Objects.isNull(userDetails)) throw new CustomException(RespCode.WRONGUSERNAME, MethodUtil.getLineInfo());
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                Asserts.fail("密码不正确");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            insertLoginLog(username);
        } catch (Exception e) {
            Asserts.fail("登录异常:" + e.getMessage());
        }
        return BeanToUtils.dtoToDo(userDetails,Member.class);
    }

    @Override
    public Member loadUserByUsername(String username) {

        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getUsername, username);
        Member member = this.getOne(queryWrapper);
        return member;
    }

    @Override
    public MemberDetails loadMemberByUsername(String username) {

        Member member = loadUserByUsername(username);
        if (Objects.isNull(member)) {
            throw new CustomException(RespCode.WRONGUSERNAME, MethodUtil.getLineInfo());
        }
        return new MemberDetails(member);
    }

    private void insertLoginLog(String username) {

        Member admin = loadUserByUsername(username);
        if (admin == null) return;
        MemberLoginLog loginLog = new MemberLoginLog();
        loginLog.setMemberId(admin.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(request.getRemoteAddr());
        memberLoginLogService.save(loginLog);

    }
}
